﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Example7_Collisions.Model;

namespace Example7_Collisions.Model
{
    
    class Level
    {
        public const int g_levelWidth  = 100;
        public const int g_levelHeight = 20;

        internal Tile[,] m_tiles = new Tile[g_levelWidth, g_levelHeight];

        internal Level()
        {
            GenerateLevel();
        }

        internal bool IsCollidingAt(FloatRectangle a_rect)
        {

            Vector2 tileSize = new Vector2(1, 1);
            for (int x = 0; x < g_levelWidth; x++)
            {
                for (int y = 0; y < g_levelHeight; y++)
                {
                    FloatRectangle rect = FloatRectangle.createFromTopLeft(new Vector2(x, y), tileSize);
                    if (a_rect.isIntersecting(rect))
                    {
                        if (m_tiles[x, y].isBlocked())
                        {
                            return true;
                        }
                    }
                }
            }
            return false;
        }

        private void GenerateLevel()
        {
            Random rand = new Random();
            for (int x = 0; x < g_levelWidth; x++)
            {
                for (int y = 0; y < g_levelHeight; y++)
                {
                    setTileToRandom(rand, x, y);
                }
                setBottomAndTopToBlocked(x);
            }
        }

        private void setBottomAndTopToBlocked(int x)
        {
            m_tiles[x, 0] = Tile.createBlocked();
            m_tiles[x, g_levelHeight - 1] = Tile.createBlocked();
        }

        private void setTileToRandom(Random rand, int x, int y)
        {
            m_tiles[x, y] = Tile.createEmpty();

            //Add some random blockes
            if (rand.Next(20) == 0)
            {
                m_tiles[x, y] = Tile.createBlocked();
                if (x > 0)
                {
                    m_tiles[x - 1, y] = Tile.createBlocked();
                }
            }

            setSidesToBlocked(x, y);
        }

        private void setSidesToBlocked(int x, int y)
        {
            if (x == 0 || x == g_levelWidth - 1)
            {
                m_tiles[x, y] = Tile.createBlocked();
            }
        }

        
    }
}
